package com.libinshen.wxpay.login.service.impl;

import com.libinshen.wxpay.common.constant.Constants;
import com.libinshen.wxpay.common.util.common.RandomUtil;
import com.libinshen.wxpay.common.util.sms.SmsSendCodeUtil;
import com.libinshen.wxpay.login.service.SmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service("SmsService")
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void smsLogin(String phone) {
        //1：如何防止多线程环境下出现问题，https://developer.aliyun.com/article/506498
        //2：使用计数器，限制一天内的短信发送次数。比如10次为例
        Integer codeCount = Constants.ZERO;
        String smsCount = redisTemplate.opsForValue().get(phone + Constants.SMSCOUNT);

        if (Integer.valueOf(smsCount) > Constants.NINE) {
            //TODO return CommonResult.error().setMessage("亲，今天短信发送次数已达上限！");
        }

        if (StringUtils.isEmpty(smsCount)) {
            smsCount = Constants.ZERO.toString();
        }

        String smsCode = redisTemplate.opsForValue().get(phone + Constants.SMSCODE);
        if (!StringUtils.isEmpty(smsCode)) {

            //TODO return CommonResult.error().setMessage("短信正在发送过程中，请不要重复点击！");
        }

        //如果获取不到，生成验证码，通过整合短信服务进行发送
        smsCode = RandomUtil.getSixBitRandom();

        boolean isSend = SmsSendCodeUtil.sendCode(phone, smsCode);
        //生成验证码放在redis中，设置有效时间为5分钟
        if (isSend) {
            redisTemplate.opsForValue().set(phone + Constants.SMSCODE, smsCode, 1, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(phone + Constants.SMSCOUNT, smsCode, codeCount++);
        } else {
            //TODO return CommonResult.error().setMessage("短信发送失败！");
        }
    }

    @Override
    public void verifyCode(String phone, String code) {
        if (StringUtils.isEmpty(code)) {
            //TODO return CommonResult.error().setMessage("验证码不能为空！");
        }

        if (StringUtils.isEmpty(phone)) {
            //TODO return CommonResult.error().setMessage("手机号不能为空！");
        }

        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            //TODO return CommonResult.error().setMessage("验证码不正确，请重新输入！");
        }
    }
}
